

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Fly542">
  <meta name="keywords" content="">
  
    <meta name="description" content="被传递句柄可以是文件句柄或socket句柄。 方法在 Linux 下，进程间可以通过以下几种方式传递句柄（文件描述符）：  父子进程继承：当一个子进程派生（fork）自父进程时，子进程会继承父进程打开的文件描述符。子进程可以直接使用这些文件描述符。  命令行参数：父进程可以将打开的文件描述符的值作为命令行参数传递给子进程。子进程可以从 argv 参数列表中获取这些文件描述符的值，并在需要时进行使用">
<meta property="og:type" content="article">
<meta property="og:title" content="进程间传递句柄">
<meta property="og:url" content="http://fly542.cn/2024/02/07/03%E8%BD%AF%E4%BB%B6%E5%BC%80%E5%8F%91/01c_cpp/18%E8%BF%9B%E7%A8%8B%E9%97%B4%E4%BC%A0%E9%80%92%E5%8F%A5%E6%9F%84/index.html">
<meta property="og:site_name" content="Fly542 技术沉淀">
<meta property="og:description" content="被传递句柄可以是文件句柄或socket句柄。 方法在 Linux 下，进程间可以通过以下几种方式传递句柄（文件描述符）：  父子进程继承：当一个子进程派生（fork）自父进程时，子进程会继承父进程打开的文件描述符。子进程可以直接使用这些文件描述符。  命令行参数：父进程可以将打开的文件描述符的值作为命令行参数传递给子进程。子进程可以从 argv 参数列表中获取这些文件描述符的值，并在需要时进行使用">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2024-02-07T08:39:02.000Z">
<meta property="article:modified_time" content="2024-02-07T08:43:16.251Z">
<meta property="article:author" content="Fly542">
<meta property="article:tag" content="linux">
<meta name="twitter:card" content="summary_large_image">
  
  
  <title>进程间传递句柄 - Fly542 技术沉淀</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hint.css@2/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"fly542.cn","root":"/","version":"1.8.14","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 6.0.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Fly542 技术沉淀</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="进程间传递句柄">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2024-02-07 16:39" pubdate>
        2024年2月7日 下午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      3.8k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      33 分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">进程间传递句柄</h1>
            
            <div class="markdown-body">
              <p>被传递句柄可以是文件句柄或socket句柄。</p>
<h1 id="方法"><a href="#方法" class="headerlink" title="方法"></a>方法</h1><p>在 Linux 下，进程间可以通过以下几种方式传递句柄（文件描述符）：</p>
<ol>
<li><p>父子进程继承：当一个子进程派生（fork）自父进程时，子进程会继承父进程打开的文件描述符。子进程可以直接使用这些文件描述符。</p>
</li>
<li><p>命令行参数：父进程可以将打开的文件描述符的值作为命令行参数传递给子进程。子进程可以从 <code>argv</code> 参数列表中获取这些文件描述符的值，并在需要时进行使用。</p>
</li>
<li><p>UNIX 域套接字（UNIX domain socket）：UNIX 域套接字是一种进程间通信的机制，除了传递字节流数据外，它还可以传递文件描述符。通过使用 <code>sendmsg()</code> 和 <code>recvmsg()</code> 系统调用，发送进程可以将文件描述符附加到消息中发送给接收进程。</p>
</li>
<li><p>消息队列（Message queues）：消息队列是一种进程间通信的机制，允许进程通过发送和接收消息进行通信。通过设置消息类型和在消息中包含文件描述符，发送进程可以将文件描述符传递给接收进程。</p>
</li>
<li><p>共享内存（Shared memory）：通过共享内存，多个进程可以访问同一块内存区域。如果句柄信息（文件描述符）保存在共享内存中，进程可以通过共享内存来传递文件描述符。</p>
</li>
<li><p>UNIX 域套接字配合 <code>SCM_RIGHTS</code> 控制消息：通过发送控制消息（control message）并设置 <code>SCM_RIGHTS</code> 控制消息标志，进程可以将文件描述符传递给其他进程。这需要使用 <code>sendmsg()</code> 和 <code>recvmsg()</code> 系统调用，并指定消息的类型为文件描述符。</p>
</li>
</ol>
<p>请注意，传递文件描述符的方法可能因操作系统或编程语言的不同而有所不同。以上列出的是一些常用的方法，您可以根据自己的需求和环境选择合适的方法来传递文件描述符。</p>
<h1 id="示例"><a href="#示例" class="headerlink" title="示例"></a>示例</h1><p>以下是使用 UNIX 域套接字（UNIX domain socket）传递文件描述符的简单示例：</p>
<p>发送进程（发送方）：</p>
<figure class="highlight c"><table><tr><td class="gutter"><div class="code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br></pre></div></td><td class="code"><pre><code class="hljs c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;sys/socket.h&gt;</span></span><br><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;sys/types.h&gt;</span></span><br><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;sys/un.h&gt;</span></span><br><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;unistd.h&gt;</span></span><br><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span><br><br><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>&#123;<br>    <span class="hljs-keyword">int</span> fd = open(<span class="hljs-string">&quot;file.txt&quot;</span>, O_RDONLY);  <span class="hljs-comment">// 打开要传递的文件</span><br>    <span class="hljs-keyword">if</span> (fd == <span class="hljs-number">-1</span>) &#123;<br>        perror(<span class="hljs-string">&quot;open&quot;</span>);<br>        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;<br>    &#125;<br><br>    <span class="hljs-keyword">int</span> sockfd = socket(AF_UNIX, SOCK_STREAM, <span class="hljs-number">0</span>);  <span class="hljs-comment">// 创建 UNIX 域套接字</span><br>    <span class="hljs-keyword">if</span> (sockfd == <span class="hljs-number">-1</span>) &#123;<br>        perror(<span class="hljs-string">&quot;socket&quot;</span>);<br>        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;<br>    &#125;<br><br>    <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">sockaddr_un</span> <span class="hljs-title">addr</span>;</span><br>    addr.sun_family = AF_UNIX;<br>    <span class="hljs-built_in">strncpy</span>(addr.sun_path, <span class="hljs-string">&quot;socket&quot;</span>, <span class="hljs-keyword">sizeof</span>(addr.sun_path) - <span class="hljs-number">1</span>);<br><br>    <span class="hljs-keyword">if</span> (connect(sockfd, (struct sockaddr*)&amp;addr, <span class="hljs-keyword">sizeof</span>(addr)) == <span class="hljs-number">-1</span>) &#123;  <span class="hljs-comment">// 连接到接收进程</span><br>        perror(<span class="hljs-string">&quot;connect&quot;</span>);<br>        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;<br>    &#125;<br><br>    <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">msghdr</span> <span class="hljs-title">msg</span> =</span> &#123; <span class="hljs-number">0</span> &#125;;<br>    <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">iovec</span> <span class="hljs-title">iov</span>[1];</span><br>    <span class="hljs-keyword">char</span> buf[<span class="hljs-number">1</span>];<br>    iov[<span class="hljs-number">0</span>].iov_base = buf;<br>    iov[<span class="hljs-number">0</span>].iov_len = <span class="hljs-keyword">sizeof</span>(buf);<br><br>    <span class="hljs-keyword">char</span> cmsgbuf[CMSG_SPACE(<span class="hljs-keyword">sizeof</span>(fd))];<br>    msg.msg_control = cmsgbuf;<br>    msg.msg_controllen = <span class="hljs-keyword">sizeof</span>(cmsgbuf);<br><br>    <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">cmsghdr</span> *<span class="hljs-title">cmsg</span> =</span> CMSG_FIRSTHDR(&amp;msg);<br>    cmsg-&gt;cmsg_len = CMSG_LEN(<span class="hljs-keyword">sizeof</span>(fd));<br>    cmsg-&gt;cmsg_level = SOL_SOCKET;<br>    cmsg-&gt;cmsg_type = SCM_RIGHTS;<br>    *((<span class="hljs-keyword">int</span> *) CMSG_DATA(cmsg)) = fd;<br><br>    msg.msg_iov = iov;<br>    msg.msg_iovlen = <span class="hljs-number">1</span>;<br><br>    <span class="hljs-keyword">if</span> (sendmsg(sockfd, &amp;msg, <span class="hljs-number">0</span>) == <span class="hljs-number">-1</span>) &#123;  <span class="hljs-comment">// 发送文件描述符</span><br>        perror(<span class="hljs-string">&quot;sendmsg&quot;</span>);<br>        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;<br>    &#125;<br><br>    close(fd);  <span class="hljs-comment">// 关闭文件</span><br>    close(sockfd);  <span class="hljs-comment">// 关闭套接字</span><br><br>    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>接收进程（接收方）：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br></pre></td><td class="code"><pre><code class="hljs c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;sys/socket.h&gt;</span></span><br><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;sys/un.h&gt;</span></span><br><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;unistd.h&gt;</span></span><br><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span><br><br><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>&#123;<br>    <span class="hljs-keyword">int</span> sockfd = socket(AF_UNIX, SOCK_STREAM, <span class="hljs-number">0</span>);  <span class="hljs-comment">// 创建 UNIX 域套接字</span><br>    <span class="hljs-keyword">if</span> (sockfd == <span class="hljs-number">-1</span>) &#123;<br>        perror(<span class="hljs-string">&quot;socket&quot;</span>);<br>        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;<br>    &#125;<br><br>    <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">sockaddr_un</span> <span class="hljs-title">addr</span>;</span><br>    addr.sun_family = AF_UNIX;<br>    <span class="hljs-built_in">strncpy</span>(addr.sun_path, <span class="hljs-string">&quot;socket&quot;</span>, <span class="hljs-keyword">sizeof</span>(addr.sun_path) - <span class="hljs-number">1</span>);<br><br>    <span class="hljs-keyword">if</span> (bind(sockfd, (struct sockaddr*)&amp;addr, <span class="hljs-keyword">sizeof</span>(addr)) == <span class="hljs-number">-1</span>) &#123;  <span class="hljs-comment">// 绑定套接字</span><br>        perror(<span class="hljs-string">&quot;bind&quot;</span>);<br>        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;<br>    &#125;<br><br>    <span class="hljs-keyword">if</span> (listen(sockfd, <span class="hljs-number">1</span>) == <span class="hljs-number">-1</span>) &#123;  <span class="hljs-comment">// 监听连接请求</span><br>        perror(<span class="hljs-string">&quot;listen&quot;</span>);<br>        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;<br>    &#125;<br><br>    <span class="hljs-keyword">int</span> connfd = accept(sockfd, <span class="hljs-literal">NULL</span>, <span class="hljs-literal">NULL</span>);  <span class="hljs-comment">// 接受连接请求</span><br>    <span class="hljs-keyword">if</span> (connfd == <span class="hljs-number">-1</span>) &#123;<br>        perror(<span class="hljs-string">&quot;accept&quot;</span>);<br>        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;<br>    &#125;<br><br>    <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">msghdr</span> <span class="hljs-title">msg</span> =</span> &#123; <span class="hljs-number">0</span> &#125;;<br>    <span class="hljs-keyword">char</span> buf[<span class="hljs-number">1</span>];<br><br>    <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">iovec</span> <span class="hljs-title">iov</span>[1];</span><br>    iov[<span class="hljs-number">0</span>].iov_base = buf;<br>    iov[<span class="hljs-number">0</span>].iov_len = <span class="hljs-keyword">sizeof</span>(buf);<br>    msg.msg_iov = iov;<br>    msg.msg_iovlen = <span class="hljs-number">1</span>;<br><br>    <span class="hljs-keyword">char</span> cmsgbuf[CMSG_SPACE(<span class="hljs-keyword">sizeof</span>(<span class="hljs-keyword">int</span>))];<br>    msg.msg_control = cmsgbuf;<br>    msg.msg_controllen = <span class="hljs-keyword">sizeof</span>(cmsgbuf);<br><br>    <span class="hljs-keyword">if</span> (recvmsg(connfd, &amp;msg, <span class="hljs-number">0</span>) == <span class="hljs-number">-1</span>) &#123;  <span class="hljs-comment">// 接收文件描述符</span><br>        perror(<span class="hljs-string">&quot;recvmsg&quot;</span>);<br>        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;<br>    &#125;<br><br>    <span class="hljs-keyword">int</span> fd;<br>    <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">cmsghdr</span> *<span class="hljs-title">cmsg</span> =</span> CMSG_FIRSTHDR(&amp;msg);<br>    <span class="hljs-keyword">if</span> (cmsg != <span class="hljs-literal">NULL</span> &amp;&amp; cmsg-&gt;cmsg_level == SOL_SOCKET &amp;&amp; cmsg-&gt;cmsg_type == SCM_RIGHTS) &#123;<br>        fd = *((<span class="hljs-keyword">int</span> *) CMSG_DATA(cmsg));<br>    &#125;<br>    <span class="hljs-keyword">else</span> &#123;<br>        <span class="hljs-built_in">fprintf</span>(<span class="hljs-built_in">stderr</span>, <span class="hljs-string">&quot;Received invalid file descriptor\n&quot;</span>);<br>        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;<br>    &#125;<br><br>    FILE* file = fdopen(fd, <span class="hljs-string">&quot;r&quot;</span>);<br>    <span class="hljs-keyword">if</span> (file == <span class="hljs-literal">NULL</span>) &#123;<br>        perror(<span class="hljs-string">&quot;fdopen&quot;</span>);<br>        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;<br>    &#125;<br><br>    <span class="hljs-keyword">char</span> line[<span class="hljs-number">100</span>分];<br>    <span class="hljs-keyword">while</span> (fgets(line, <span class="hljs-keyword">sizeof</span>(line), file) != <span class="hljs-literal">NULL</span>) &#123;<br>        <span class="hljs-built_in">printf</span>(<span class="hljs-string">&quot;%s&quot;</span>, line);  <span class="hljs-comment">// 打印文件内容</span><br>    &#125;<br><br>    fclose(file);  <span class="hljs-comment">// 关闭文件</span><br>    close(connfd);  <span class="hljs-comment">// 关闭连接套接字</span><br>    close(sockfd);  <span class="hljs-comment">// 关闭监听套接字</span><br><br>    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>在上面的示例中，发送进程打开了文件 “file.txt”，并通过 UNIX 域套接字将文件描述符发送给接收进程。接收进程接收文件描述符，并使用 <code>fdopen</code> 函数将文件描述符转换为文件指针，最后打印文件的内容。</p>
<p>这仅是一个简单的示例，实际使用时需要进行错误处理和适当的错误检查。确保运行示例时，套接字的命名、路径和权限正确，并确保发送进程在接收进程之前启动。</p>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/devops/">devops</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/linux/">linux</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2024/04/07/04DevOps/32crontab%E4%BD%BF%E7%94%A8/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">crontab使用总结</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2023/12/06/04DevOps/31docker%E9%95%9C%E5%83%8F%E7%9A%84%E5%AF%BC%E5%85%A5%E5%92%8C%E5%AF%BC%E5%87%BA/">
                        <span class="hidden-mobile">docker镜像的导入和导出</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
  </div>
  

  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  






  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
        typing(title);
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
